import express from 'express';
import path from 'path';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan'; // express默认的日志中间件
import rateLimit from 'express-rate-limit';
import { errorMiddleware } from './middlewares/error.middleware';
import routes from './routes';
import type { Request, Response, NextFunction } from 'express';

const app = express();

// 中间件配置
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan('combined'));
// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// 速率限制
const limiter = rateLimit({
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '900000'),
  max: parseInt(process.env.RATE_LIMIT_MAX || '100'),
});
app.use(limiter);

// 统一路由管理
app.use('/api', routes);


// 错误处理（必须放在最后）
app.use(errorMiddleware);

export default app; 